//
//  MemoryView.m
//  MXClassroom
//
//  Created by 你个LB on 16/9/11.
//  Copyright © 2016年 你个LB. All rights reserved.
//

#import "MemoryView.h"

@implementation MemoryView

- (void)layoutSubviews{
    // 获取设备的可用储存空间
//    NSLog(@"可用储存空间:%@",[self freeDiskSpaceInBytes]);
    
    // 获取本地音视频文件大小
//    NSLog(@"本地音视频文件大小:%@",[self getDownLoadVideoSize]);
    self.backgroundColor = kColor_Memory_bg_color;
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    label.text = [NSString stringWithFormat:@"已占用空间%@,可用空间%@",[self getDownLoadVideoSize], [self freeDiskSpaceInBytes]];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = kColor_Memory_text_color;
    label.font = [UIFont systemFontOfSize:11 weight:2];
    [self addSubview:label];
}

// 获取设备的可用储存空间
- (NSString *)freeDiskSpaceInBytes{
    
    // 获取当前缓存量
    // 01 获取当前项目总量
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSDictionary *fileSystemAtt = [fileManager attributesOfFileSystemForPath:path error:nil];
    // 获取总空间的大小 M
//    float mainSize = [[fileSystemAtt objectForKey:NSFileSystemSize] longLongValue] / (1024.0 * 1024.0);
    // 02 获取当前可用空间 M
    float freeSize = [[fileSystemAtt objectForKey:NSFileSystemFreeSize] floatValue] / (1024.0 * 1024.0 * 1024);
    
    return [NSString stringWithFormat:@"%0.1fG",freeSize];
}

// 获取本地音视频文件大小
- (NSString *)getDownLoadVideoSize
{
    long long size = 0;
    // 1.获取缓存文件夹路径
    NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Library/Caches/VideoDownLoad"];
    // 2.计算文件的大小
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // 01 获取当前文件夹下面所有文件的子路径
    NSArray *subPaths = [fileManager subpathsAtPath:filePath];
    // 便利所有的文件的路径
    for (NSString *subFilePath in subPaths) {
        // 拼接完整的路径
        NSString *path = [filePath stringByAppendingPathComponent:subFilePath];
        // 获取文件的大小
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];
        size += [fileDic fileSize];
    }
    NSLog(@"%lld",size);
    
    return [NSString stringWithFormat:@"%0.1fM",size / (1000.0 * 1000.0)];
}
@end
